package light.head.dao.inv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvOrderInfo;
@Service
public class InvOrderInfoDAO extends BaseDAO<InvOrderInfo, Integer>{
	public RESULT findByMap(List<Integer> ocs, Map<String, String> map, PageBean pb){
		if (ocs == null || ocs.size() == 0) return null;
		StringBuffer hql = new StringBuffer("FROM InvOrderInfo io WHERE io.oc IN (");
		List<Object> list = new ArrayList<Object>();
		for (Integer i : ocs) {
			hql.append("?,");
			list.add(i);
		}
		hql.deleteCharAt(hql.length() - 1).append(")");
		if (map != null) {
			String cn = map.get(Parm.CN);
			String on = map.get(Parm.ON);
			String time1 = map.get(Parm.TIME1);
			String time2 = map.get(Parm.TIME2);
			String dn = map.get(Parm.DN);
			String bn = map.get(Parm.BN);
			String type = map.get(Parm.TYPE);
			String deleted = map.get(Parm.DELETED);
			
			
			if (isNotNull(deleted)) {
				list.add(Boolean.parseBoolean(deleted));
				hql.append(" AND io.deleted = ?");
			}
			if (isNotNull(dn)) {
				hql.append(" AND io.dn LIKE ?");
				list.add("%" + dn + "%");
			}
			if (isNotNull(bn)) {
				hql.append(" AND io.bc IN (SELECT b.code FROM InvBusiness b WHERE b.name LIKE ?)");
				list.add("%" + bn + "%");
			}
			if (isNotNull(cn)) {
				list.add("%" + cn + "%");
				hql.append(" AND io.cu IN (SELECT ui.code FROM UserInfo ui WHERE ui.realName LIKE ?)");
			}
			if (isNotNull(on)) {
				list.add("%" + on + "%");
				hql.append(" AND io.oc IN (SELECT org.code FROM Organ org WHERE org.name LIKE ?)");
			}
			if (isNotNull(time1)) {
				hql.append(" AND io.ct >= ?");
				list.add(DateUtils.getDateByStr(time1, null));
			}
			if (isNotNull(time2)) {
				hql.append(" AND io.ct <= ?");
				list.add(DateUtils.getDateByStr(time2, null));
			}
			if (isNotNull(type)) {
				hql.append(" AND io.type = ?");
				list.add(Byte.parseByte(type));
			}
		}
		hql.append(" ORDER BY io.code DESC");
		return findToPageBean(hql.toString(), pb, list);
	}
	
	public RESULT update(InvOrderInfo io) {
		if (null == io || io.getCode() == null) return null;
		InvOrderInfo db = this.get(io.getCode());
		if (null == db) return RESULT.NOT_FIND;
		
		boolean ok = false;
		if (null == db.getBc() && null != io.getBc() || (db.getBc() != io.getBc())){
			db.setBc(io.getBc());
			ok = true;
		}
		if (null == db.getType() && null == io.getType() || (db.getType() != io.getType())) {
			db.setType(io.getType());
			ok = true;
		}
		if (ok)
			return super.upd(db);
		
		return RESULT.SUCCESS;
	}


}
